package com.lenovo.smarttraffic.ui.activity.stage6;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;

import static android.view.KeyEvent.KEYCODE_BACK;

public class MainActivity extends BaseActivity {

    private WebView mWebView;
    private WebSettings mWebSettings;

    @Override
    protected int getLayout() {
        return R.layout.activity_stage6;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mWebView = findViewById(R.id.web_view);

        mWebSettings = mWebView.getSettings();

        // 设置与Js交互的权限
        mWebSettings.setJavaScriptEnabled(true);

        // 通过addJavascriptInterface()将Java对象映射到JS对象
        //参数1：Javascript对象名
        //参数2：Java对象名
        mWebView.addJavascriptInterface(this, "main");

        mWebView.loadUrl("file:///android_asset/stage6_main.html");
    }

    @JavascriptInterface
    public void start(int which) {
        switch (which) {
            case 1:
                startActivity(new Intent(this, SignActivity.class));
                break;
            case 2:
                startActivity(new Intent(this, CarFindActivity.class));
                break;
            case 3:
                startActivity(new Intent(this, UserCenterActivity.class));
                break;
            case 4:
                startActivity(new Intent(this, ParkingActivity.class));
                break;
            case 5:
                startActivity(new Intent(this, MyTrafficActivity.class));
                break;
            case 6:
                startActivity(new Intent(this, PayCenterActivity.class));
                break;
        }
    }

    @Override
    protected void onPause() {
        mWebView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mWebView.onResume();
        super.onResume();
    }

    //销毁WebView
    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
